import { Button, Statistic, Tooltip,AutoComplete, message, Card, Row, Col } from 'antd';
import React, {
  useState,
  useRef
} from 'react';
import { PageContainer } from '@ant-design/pro-layout';
import type { ProColumns } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import { queryRule, selectStudent,selectActivity,queryInfo,userPlayExport} from './service';
import { Link } from "react-router-dom"
import moment from 'moment';
import { downloadFile } from '../../../utils/utils'
import ProCard from '@ant-design/pro-card';
import { useEffect } from 'react';
const { Option } = AutoComplete;
const TableList=(props) => {
  const actionRef = useRef();
  const { activityId } = props.location.query
  const [options, setOptions] = useState<{ value: string }[]>([]);
  const [uidOptions, setUidOptions] = useState<{ value: string }[]>([]);
  const [firstRender,setFirstRender] = useState<boolean>(true)

  const [baseInfo, setBaseInfo] = useState<any>()
  const [uid, setUid] = useState<any>()
  const statusMap = {
    '0': '未开始',
    '1': '已开始',
    '2': '已完成'
  }
  const onUidSelect = (data: any, option: any) => {
    setUid(option.key)
  };
  const onUidSearch = async (key: string) => {
    let data = await selectStudent( key )
    function getStudentSearchOptions(keys:any, data:any) {
      return  !keys ? [] : data.result.map((item: { uid: any; nickname: any; phone: any}) => ({
        id: item.uid,
        label: (item.nickname||'') + `  (${item.phone})`,
        value: item.nickname + `  (${item.phone})`
      }))
    }
    let options =  getStudentSearchOptions(key,data)
    setUidOptions(options);
  };


  const userPlayExportHandler = async function () {
    if (!activityId) {
      message.error('请选择或者输入课程id')
      return
    }
    let params = {}
    if (uid) {
      params = { activityId: String(activityId), uid: String(uid) }
    } else {
      params = { activityId: String(activityId) }
    }
    const url = await userPlayExport(params)
    downloadFile(`活动学员对弈详情-${moment(new Date().getTime()).format('YYYY-MM-DD HH-mm-ss')}`,url,'.xls')
  }
  const columns: ProColumns<{}>[] = [
    {
      title: '用户id',
      dataIndex: 'uid',
      hideInSearch: true
    },

    {
      title: '用户昵称',
      dataIndex: 'uidkey',
      hideInTable: true,
      renderFormItem: (text, props) =>
        <AutoComplete
          onSelect={onUidSelect}
          onSearch={onUidSearch}
          placeholder="请选择"
          onChange={(value) => {
            if (!value) {
              setUid()
            }
           }}
        >
           {uidOptions.map((item) => (
            <Option key={item.id}  label={item.label} value={item.label}>
              {item.label}
            </Option>
          ))}
        </AutoComplete>,
    },
    {
      title: '用户昵称',
      dataIndex: 'nickname',
      hideInSearch: true,
    },
    {
      title: '手机号',
      dataIndex: 'phone',
      hideInSearch: true,
    },
    {
      title: '班级',
      dataIndex: 'groupName',
      hideInSearch: true,
    },
    {
      title: '对弈积分',
      dataIndex: 'playScore',
      hideInSearch:true
    },
    {
      title: '棋士品级',
      dataIndex: 'playGradeName',
      hideInSearch: true,
    },
    {
      title: '总盘数',
      dataIndex: 'gameNum',
      hideInSearch: true,
    },
    {
      title: '总胜数',
      dataIndex: 'winNum',
      hideInSearch: true,
      render: (_, record) => {
        if (!record.playScore  && !record.winNum) {
          return <>-</>
        } else if (record.playScore >=1 && !record.winNum) {
          return <>0</>
        } else if (record.playScore>=1 && record.winNum>=1){
          return <>{ record.winNum}</>
        }
      }

    },
    {
      title: '近一周对局',
      dataIndex: 'weekNum',
      hideInSearch: true,
      render: (_, record) => {
        if (!record.playScore  && !record.weekNum) {
          return <>-</>
        } else if (record.playScore >=1 && !record.weekNum) {
          return <>0</>
        } else if (record.playScore>=1 && record.weekNum>=1){
          return <>{ record.weekNum}</>
        }
      }
    },
    {
      title: '近一周胜局',
      dataIndex: 'weekWinNum',
      hideInSearch: true,
      render: (_, record) => {
        if (!record.playScore  && !record.weekWinNum) {
          return <>-</>
        } else if (record.playScore >=1 && !record.weekWinNum) {
          return <>0</>
        } else if (record.playScore>=1 && record.weekWinNum>=1){
          return <>{ record.weekWinNum}</>
        }
      }
    },
    {
      title: '最近对局时间',
      dataIndex: 'lastTime',
      hideInSearch: true,
      render: (lastTime,record) => (<>{record.lastTime ? moment(lastTime*1000).format('YYYY-MM-DD HH:mm:ss'):'-'}</>)
    },
    {
      title: '对局列表',
      hideInSearch: true,
      dataIndex: 'option',
      render: (_: any, record: any) => (
         <Link target="_blank" to={`/game/game-list?uid=${record.uid}`}>
            查看对局列表
          </Link>
      )
    },
  ];
  useEffect(()=>{
    const getInfo = async ()=>{
      const info = await queryInfo({ activityId:activityId })
      setBaseInfo(info.data)
    }
    if(activityId){
      getInfo()
    }
  },[])


  return (

    <PageContainer>


      <ProTable<{}>
        headerTitle="数据列表"
        actionRef={actionRef}
        rowKey="key"
        request={async params => {

          let _activityId = activityId ? activityId : params.activityId
          params.activityId = _activityId
          params.uid = uid
          const msg = await queryRule({
            ...params,
            pageNum: params.current
          })
           return {
            data: msg.data.users === null?[]:msg.data.users,
            success: true,
            total: msg.data.count
          }
        }}

        columns={columns}

        toolBarRender={
          () => (
            [
              <Button key="primary" type="primary" onClick={userPlayExportHandler}>
                导出活动学员对弈详情
              </Button>
            ]
          )
        }

        onReset={() => {
          window.location.reload()
        }}
        tableExtraRender={(props, dataSource) =>
          baseInfo&&
          <Card>
            <div style={{display:'flex'}}>
              <div
                style={{marginRight:'20px'}}
              >主讲老师 :
              <span style={{fontSize:'17px',paddingLeft:'10px'}}>
                {baseInfo.teacherName}
                </span>
              </div>
              <div
                style={{marginRight:'20px'}}
                >课程进行至:
                <span
                style={{fontSize:'17px',paddingLeft:'10px'}}>
                  {baseInfo.status == 1? baseInfo.classroomName : statusMap[baseInfo.status]}
                </span>
               </div>
            </div>
          </Card>
        }
        onSubmit={
          async (params) => {

            let _activityId = activityId ? activityId : params.activityId
            if (
              !params.activityId
              && !activityId
              && !firstRender
            ) {
              message.error('请选择或者输入课程id')
              return {}
            } else {
              params.activityId = _activityId
              setFirstRender(false)
              const info = await queryInfo({ activityId:params.activityId })
              setBaseInfo(info.data)
              return params
            }

          }

      }
      />
    </PageContainer>
  );
};

export default TableList;
